templateViewInit = async ()=>{
    var json = await loadJson();
    top.ProcessDefinition = function(){
        var bpmnModeler;
        var options_={
            scale:1,
            canvasBackgroundColor:'#F7F7F8',
            minimap:true,//添加小地图
            minimapOpen:true,//打开小地图
            panel:true, // 属性工具栏
            //添加自定义按钮
            addCustomButton:[
                {
                    className:"layui-icon layui-icon-delete",
                    title:"撤销",
                    click: async function handlerUndo(bpmnModeler){
                        bpmnModeler.get('commandStack').undo()
                    }
                },
                {
                    className:"layui-icon layui-icon-delete",
                    title:"恢复",
                    click: async function handlerRedo(bpmnModeler){
                        bpmnModeler.get('commandStack').redo()
                    }
                },
                {
                    className:"layui-icon layui-icon-delete",
                    title:"清空",
                    click: function save(bpmnModeler){
                        openConfirm((index)=>{
                            // bpmnModeler.clear();
                            bpmnModeler.importXML(getXmlStr());
                            layer.close(index);
                        },'','清空流程内容');
                    }
                },
                {
                    className:"layui-icon layui-icon-save",
                    title:"保存",
                    click: async function save(bpmnModeler){
                        function openConfig(){
                            let parent =  $('#bio-properties-panel-id').parent().parent().parent();
                           let c = parent.attr('class')
                            if (c.indexOf('open')===-1){
                                parent.addClass('open');
                            }
                        }

                        const key = $('#bio-properties-panel-id').val();
                        const name = $('#bio-properties-panel-name').val();
                        if (!name || !key){
                            layer.msg("名称和编号不能为空", {icon: 0})
                            openConfig()
                            return;
                        }
                        if (!$('#bio-properties-panel-isExecutable').prop('checked')){
                            layer.msg("请选择可执行文件选项", {icon: 0})
                            openConfig()
                            return;
                        }

                        try {
                            const result = await bpmnModeler.saveXML({ format: true })
                            let { xml } = result
                            top.API.activiti().deploy({
                                name:name,
                                key:key,
                                description:true,
                                xml:formXML(xml)
                            },(res)=>{
                                layer.msg(res.message, {icon: 1});
                            })
                        } catch (err) {
                            console.log(err)
                        }
                    }
                },
                {
                    className:"layui-icon layui-icon-file-image",
                    title:"导出",
                    click: async function save(bpmnModeler){
                        // 这里就获取到了之前设置的隐藏链接
                        const downloadLink = document.getElementById("downloadLink");
                        const name = $('#bio-properties-panel-name').val();
                        if (!name){
                            layer.msg("名称不能为空", {icon: 0})
                            return;
                        }
                        const result = await bpmnModeler.saveXML({ format: true })
                        let { xml } = result
                        xml = formXML(xml)
                        var xmlBlob = new Blob([xml], {
                            type: 'application/bpmn20-xml;charset=UTF-8,',
                        })

                        if (xmlBlob) {
                            downloadLink.download = name+'.xml';
                            downloadLink.href = window.URL.createObjectURL(xmlBlob);
                            // 触发点击事件开始下载
                            downloadLink.click();
                        }
                        const resultsvg = await bpmnModeler.saveSVG();
                        const { svg } = resultsvg;
                        var svgBlob = new Blob([svg], {
                            type: "image/svg+xml"
                        });

                        if (svgBlob) {
                            downloadLink.download = name+'.svg';
                            downloadLink.href = window.URL.createObjectURL(svgBlob);
                            // 触发点击事件开始下载
                            downloadLink.click();
                        }
                    }
                }
            ],
            //固定按钮
            button:[
                {
                    className:"layui-icon layui-icon-delete",
                    title:"查看",
                    click: async function save(bpmnModeler){
                        // 可以点保存查看下控制台 xml
                        const {xml} = await bpmnModeler.saveXML();
                        let xml_form = formXML(xml);
                        openForm({
                            title:"XML",
                            btn:-1,
                            area:['60%','80%'],
                            before:(index,layero,that,isEdit)=>{
                                layui.code({
                                    elem: '.code-demo',
                                    tools:['copy'],
                                    lang:'xml',
                                    code:top.tools.form.formatXml(xml_form),
                                });
                            }
                        },'','<pre class="layui-code code-demo"></pre>')
                    }
                },
                {
                    className:"layui-icon layui-icon-delete",
                    title:"放大",
                    click: async function handlerZoom(bpmnModeler){
                        let radio = 0.1
                        const newScale = !radio ? 1.0 : options_.scale + radio
                        bpmnModeler.get('canvas').zoom(newScale)
                        options_.scale = newScale
                    }
                },
                {
                    className:"layui-icon layui-icon-delete",
                    title:"缩小",
                    click: async function handlerZoom(bpmnModeler){
                        let radio = -0.1
                        const newScale = !radio ? 1.0 : options_.scale + radio
                        bpmnModeler.get('canvas').zoom(newScale)
                        options_.scale = newScale
                    }
                },
                {
                    className:"layui-icon layui-icon-delete",
                    title:"还原",
                    click: async function handlerZoom(bpmnModeler){
                        let radio = 0
                        const newScale = !radio ? 1.0 : options_.scale + radio
                        bpmnModeler.get('canvas').zoom(newScale)
                        options_.scale = newScale
                    }
                },
                {
                    className:"layui-icon layui-icon-delete",
                    title:"居中",
                    click: async function handlerCenter(bpmnModeler){
                        let canvas = bpmnModeler.get('canvas')
                        canvas.zoom('fit-viewport', 'auto')
                    }
                },
            ],
            //监听事件 {elem:'',event:'',callback:()=>{}}
            listeners:[
                {elem:'#bio-properties-panel-name',event:'blur',callback:function (){
                        top.API.activiti().verify({name:$(this).val()},(res)=>{
                            if (res.data){
                                layer.msg("名称重复",{icon:2})
                            }
                        })
                    }},
                {elem:'#bio-properties-panel-id',event:'blur',callback:function (){
                        top.API.activiti().verify({key:$(this).val()},(res)=>{
                            if (res.data){
                                layer.msg("编号重复",{icon:2})
                            }
                        })
                    }}
            ],
            extensions:true,//添加扩展属性
        }
        function init(options,callback){
            options = {...options_,...options}
            let bpmn = {
                container: '#canvas',
                additionalModules: [
                    {
                        translate: ['value', translate]
                    }
                ],
            }
            // 属性工具栏
            if (options.panel){
                bpmn.propertiesPanel={parent: '#properties-panel'}
                bpmn.additionalModules.push(BpmnJSPropertiesPanel.BpmnPropertiesPanelModule)
                // 基础信息, id/name/version
                bpmn.additionalModules.push(BpmnJSPropertiesPanel.BpmnPropertiesProviderModule)
            }
            // 添加小地图
            if (options.minimap){
                bpmn.additionalModules.push(DiagramJSMinimap)
            }
            // 添加扩展属性
            if (options.panel && options.extensions){
                bpmn.additionalModules.push(BpmnJSPropertiesPanel.CamundaPlatformPropertiesProviderModule)
                bpmn.moddleExtensions={
                    camunda: json
                    // activiti: json
                }
            }

            bpmnModeler = new BpmnJS(bpmn)
            addCustomButton(bpmnModeler,options.addCustomButton);
            if (options.minimap && options.minimapOpen){
                bpmnModeler.get('minimap').open()
            }
            const canvas = bpmnModeler.get('canvas');
            // 设置画布背景色
            canvas._container.style.backgroundColor = options.canvasBackgroundColor;
            // 创建空白流程图
            createNewDiagram()
            //添加监听事件
            addListener(options.listeners)
            callback(bpmnModeler,options);
        }
        // 创建新流程图
        async function createNewDiagram() {
            try {
                const result = await bpmnModeler.importXML(getXmlStr())
                const { warnings } = result
                console.log(warnings)
                success()
            } catch (err) {
                console.log(err.message, err.warnings)
            }
        }
        function success() {
            addModelerListener()
            addEventBusListener()
            addPanelListener()
            handlerCenter()
        }
        function addModelerListener() {
            bpmnModeler.on('element.click', (e) => {
                console.log('modelerListener', e)
            })
            bpmnModeler.on('shape.added',elementClick)
        }
        function addEventBusListener() {
            const eventBus = bpmnModeler.get('eventBus')
            eventBus.on('element.click', elementClick)
        }
        function addPanelListener() {
            let panelDom = document.getElementById('properties-panel')
            panelDom.addEventListener('click', setPanelRoleIds)
        }
        function handlerCenter() {
            let canvas = bpmnModeler.get('canvas')
            canvas.zoom('fit-viewport', 'auto')
        }
        function elementClick(e) {
            console.log(e)
            const that = this
            if (e.type === 'shape.added') {
                console.log("新增")
                // e.element.id = "sid_"+generateUUID();
            }else if (e.element.type === 'bpmn:UserTask') {
                that.currentElement = e.element
            } else {
                that.currentElement = null
            }
        }
        function generateUUID() {
            // 生成 16 字节的 Uint8Array（128 位）
            const buffer = new Uint8Array(16);
            window.crypto.getRandomValues(buffer);

            // 按照 UUID v4 格式处理字节
            buffer[6] = (buffer[6] & 0x0f) | 0x40; // 设置版本号（第 7 字节，高 4 位为 0x4）
            buffer[8] = (buffer[8] & 0x3f) | 0x80; // 设置变体（第 9 字节，高 2 位为 0x8）

            // 转换为十六进制字符串并格式化
            return Array.from(buffer, byte =>
                byte.toString(16).padStart(2, '0')
            ).join('').match(/.{8}(?:.{4}){3}.{12}/)[0];
        }
        function setPanelRoleIds(e) {
            console.log(e)
            if (e.target.id === 'camunda-candidateGroups') {
                e.target.autocomplete = 'off'
                let value = e.target.value
                if (value) {
                    value = value.split(',')
                }
                console.log(value)
                // this.formData.roleId = value
                // this.userTaskVisible = true
            }
        }

        // 添加按钮
        function addCustomButton(bpmnModeler,addCustomButton){
            // let palette = $('.djs-palette.open').find('.djs-palette-entries')
            let palette = $('#custom-button')
            let but = [...options_.button,...addCustomButton]
            if (but.length === 0) return;
            // palette.append('<hr class="separator">')
            for (let i = 0; i < but.length; i++) {
                // 创建子元素
                // var newElement = $('<div class="group" data-group="custom"><div class="entry '+but[i].className+'"  title="'+but[i].title+'"></div></div>');
                var newElement = $(' <button type="button" class="layui-btn layui-btn-normal layui-btn-sm">'+but[i].title+'</button>');
                newElement.on('click', ()=>{
                    but[i].click(bpmnModeler)
                });
                palette.append(newElement)
            }
        }
        //添加元素监听
        function addListener(listeners){
            if (listeners.length===0){
                return;
            }
            for (let i = 0; i < listeners.length; i++) {
                $('#properties-panel').on(listeners[i].event,listeners[i].elem,listeners[i].callback)
            }
        }

        function formXML(data) {
            let temp = data.replace(/camunda:/gi, 'activiti:')
            temp = temp.replace(/formField/gi, 'formProperty')
            temp = temp.replace(/<activiti:FormData>/gi, '')
            temp = temp.replace(/<\/activiti:FormData>/gi, '')
            temp = temp.replace(/task/gi, 'userTask')
            return temp
        }
        // 回显的时候activiti转camunda
        function reformXML(data) {
            let temp = data.replace(/activiti:/gi, 'camunda:')
            temp = temp.replace(/formProperty/gi, 'formField')
            temp = temp.replace(/<extensionElements>/gi, `<extensionElements><camunda:FormData>`)
            temp = temp.replace(/<\/extensionElements>/gi, `</camunda:FormData></extensionElements>`)
            return temp
        }
        return {
            init,formXML,reformXML
        }
    };
}

async function loadJson(){
    let json = null;
    await $.getJSON(system_config.basePath +"/bpmn-js/camunda.json").done(function (data, textStatus, jqXHR){
        json = data
    })
    return json;
}
